//
//  Background.swift
//  FrogGame
//
//  Created by wanght on 2016/12/2.
//  Copyright © 2016年 wanght. All rights reserved.
//

import SpriteKit

class Backgound : SKNode {
    
    let disForPerStep : Int = 30
    let widthScene : CGFloat = 1334
    
    let oneTimeInterval = 0.15
    var bgNodeArray = [SKSpriteNode]()
    
    override init() {
        super.init()
        
        let bg1Node = SKSpriteNode(imageNamed: "bg1.png")
        bg1Node.anchorPoint = CGPoint(x: 0, y: 0)
        bg1Node.position.y = 350
        
        let bg2Node = SKSpriteNode(imageNamed: "bg2.png")
        bg2Node.anchorPoint = CGPoint(x: 0, y: 0)
        bg2Node.position.x = bg1Node.frame.width
        bg2Node.position.y = 345
        
        let bg3Node = SKSpriteNode(imageNamed: "bg1.png")
        bg3Node.anchorPoint = CGPoint(x: 0, y: 0)
        bg3Node.position.x = bg1Node.frame.width + bg2Node.frame.width
        bg3Node.position.y = 350
        
        let bg4Node = SKSpriteNode(imageNamed: "bg2.png")
        bg4Node.anchorPoint = CGPoint(x: 0, y: 0)
        bg4Node.position.x = bg1Node.frame.width * 2 + bg2Node.frame.width
        bg4Node.position.y = 345

        
        addChild(bg1Node)
        addChild(bg2Node)
        addChild(bg3Node)
        addChild(bg4Node)
        
        
        bgNodeArray.append(bg1Node)
        bgNodeArray.append(bg2Node)
        bgNodeArray.append(bg3Node)
        bgNodeArray.append(bg4Node)
        
        
    }

    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func move(stepNumber: Int) {
        
        let moveAction = SKAction.moveBy(x: -CGFloat(stepNumber * disForPerStep), y: 0, duration: oneTimeInterval * 2)
        
        for bg in bgNodeArray {
            
            if stepNumber == -1 {
                bg.run(SKAction.sequence([moveAction, moveAction.reversed()]))
            } else {
                bg.run(moveAction)
            }
        }
        
        
        if bgNodeArray[3].position.x + bgNodeArray[3].frame.width <= 0 {
            bgNodeArray[2].position.x = widthScene
            bgNodeArray[3].position.x = widthScene + bgNodeArray[2].frame.width
        } else if bgNodeArray[1].position.x + bgNodeArray[1].frame.width <= 0 {
            bgNodeArray[0].position.x = widthScene
            bgNodeArray[1].position.x = widthScene + bgNodeArray[0].frame.width
        }
    }
    
}
